package com.start.ws;

import com.alibaba.fastjson2.JSONObject;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


@Slf4j
@Component
@ServerEndpoint(StartWebSocketEndpoint.START_WS_URL)
public class StartWebSocketEndpoint {
    public static final String START_WS_URL = "/startWebSocket/{clientType}/{startUserType}/{userId}" ;

    /**
     * 建立连接调用的方法，群成员加入
     */
    @OnOpen
    public void onOpen(@PathParam("clientType") String clientType,
                       @PathParam("startUserType") String startUserType,
                       @PathParam("userId") String userId,
                       Session session) {
        log.info("有客户端连接:客户端类型：{},用户id:{}", clientType, userId);
        StartGlobalSocketDispatcher dispatcher = StartGlobalSocketDispatcher.getDispatcher();

        dispatcher.onConnect(startUserType, clientType, userId, session);
    }

    /**
     * 服务器收到消息，给客户端发送消息
     *
     * @param msgEntity：消息JSON
     */
    @OnMessage
    public void onMessage(
            @PathParam("clientType") String clientType,
            @PathParam("startUserType") String startUserType,
            @PathParam("userId") String userId,
            String msgEntity) {
        try {
            StartGlobalSocketDispatcher dispatcher = StartGlobalSocketDispatcher.getDispatcher();
            dispatcher.onReceive(startUserType, clientType, userId, JSONObject.parseObject(msgEntity));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 关闭连接调用的方法，群成员退出
     */
    @OnClose
    public void onClose(
            @PathParam("clientType") String clientType,
            @PathParam("startUserType") String startUserType,
            @PathParam("userId") String userId,
            Session session) {
        StartGlobalSocketDispatcher dispatcher = StartGlobalSocketDispatcher.getDispatcher();
        dispatcher.onClose(startUserType, clientType, userId, session);
    }

    /**
     * 传输消息错误调用的方法
     */
    @OnError
    public void OnError(Throwable error) {
        log.info("连接错误");
        error.printStackTrace();
    }
}
